package edu.haiu.training.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserBean {
	private static final String username1 ="root";
	private static final String password1 ="123456";
	private static final String database1 ="jdbc:mysql://localhost:3306/mydb";
	
	List<User>users = new ArrayList<User>();
	
	public List<User> getUsers() {
		return users;
	}
	public void setUsers(List<User> users) {
		this.users = users;
	}


	public String execute() throws Exception{
		
		Connection connection = DriverManager.getConnection(database1,username1,password1);
		String qs= "select * from mydb.user";
		PreparedStatement st= connection.prepareStatement(qs);
		ResultSet rs = st.executeQuery(qs);
		
		while(rs.next()){
			 User user = new User();
			 user.setId1(rs.getInt("Id"));
			 user.setUsername(rs.getString("Username"));
			 user.setPassword(rs.getString("Password"));
			 user.setFirstName(rs.getString("FirstName"));
			 user.setLastName(rs.getString("LastName"));
			 user.setAddress(rs.getString("Address"));
			 user.setBirthday(String.valueOf(new java.sql.Date(rs.getDate("Birthday").getTime())));
			 user.setAdministrator(rs.getBoolean("Administrator"));		 
			 user.setState(UserState.values()[rs.getInt("State")]);
			 users.add(user);
		}
		
		return "success";
	}
}

//public void editUser(User user) throws Exception{
//PreparedStatement ps = connection.prepareStatement("update mydb.user set username=? password=? firstName=? lastName=? address=? birthday=? administrator=? state=? "+"where id1=?" );//+String.valueOf(id1)
//ps.setInt(1, user.getId1());
//ps.setString(2, user.getUsername());
//ps.setString(3, user.getPassword());
//ps.setString(4, user.getFirstName());
//ps.setString(5, user.getLastName());
//ps.setString(6, user.getAddress());
//ps.setDate(7, new java.sql.Date(user.getBirthday().getTime()));
//ps.setBoolean(8, user.isAdministrator());
//ps.setInt(9, getState().ordinal());
//ps.executeUpdate();
//connection.close();
//}
//public String edit() throws Exception{
//	User user = new User();
//	try {
//		HttpServletRequest rq = ServletActionContext.getRequest();
//		user.setId1(Integer.parseInt(rq.getParameter("id1")));
//		user.setUsername(rq.getParameter("Username"));
//		user.setPassword(rq.getParameter("Password"));
//		user.setFirstName(rq.getParameter("FirstName"));
//		user.setLastName(rq.getParameter("LastName"));
//		user.setAddress(rq.getParameter("Address"));
//		user.setBirthday(rq.getParameter("Birthday"));
//		user.setAdministrator(Boolean.valueOf(rq.getParameter("Administrator")));
//		user.setState(UserState.valueOf(rq.getParameter("State")));
//		user.editUser(user);
//	} catch(NumberFormatException e) {
//		e.printStackTrace();
//	}
//	return "success";
//}
